﻿using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using VueAdminService.Attributes;
using VueAdminService.DTO;
using VueAdminService.Utils;
using VueAdminService.VO;

namespace VueAdminService.Controllers
{
	[ApiController]
	[Route("api/[controller]")]
	[TokenRequired]
	public class PermissionController : BaseController
	{
		protected readonly IConfiguration _configuration;
		public PermissionController(IConfiguration configuration, IServiceProvider serviceProvider) : base(serviceProvider)
		{
			_configuration = configuration;
		}

		/// <summary>
		/// 权限分页列表
		/// </summary>
		/// <param name="page"></param>
		/// <param name="limit"></param>
		/// <param name="keyword"></param>
		/// <returns></returns>
		[HttpGet("pagelist")]
		public ResponsePageResult<List<PermissionDTO>> GetList([FromQuery] int pageIndex, [FromQuery] int pageSize, [FromQuery] string? keyword)
		{
			try
			{
				int total = 0;
				var list = _dbClient.Queryable<PermissionDTO>()
					.WhereIF(!string.IsNullOrWhiteSpace(keyword), p => p.PermissionName.Contains(keyword) || p.PermissionCode.Contains(keyword) || p.Url.Contains(keyword))
					.OrderByDescending(p => p.PermissionId)
					.ToPageList(pageIndex, pageSize, ref total);

				return SuccessPageResult<List<PermissionDTO>>(list, total);
			}
			catch (Exception ex)
			{
				LogError(ex, "获取权限列表失败");
				return ErrorPageResult<List<PermissionDTO>>("获取权限列表失败");
			}

		}
		/// <summary>
		/// 添加权限
		/// </summary>
		/// <param name="vo">请求实体</param>
		/// <returns></returns>
		[HttpPost]
		public ResponseResult<bool> Add([FromBody] RequestAddPermissionVO vo)
		{
			try
			{
				_dbClient.Insertable<PermissionDTO>(new PermissionDTO()
				{
					PermissionId = SnowFlakeSingle.Instance.NextId().ToString(),
					PermissionName = vo.PermissionName,
					PermissionCode = vo.PermissionCode.ToLower(),
					Url = vo.Url,
					Icon=vo.Icon,
					Order=vo.Order,
					Type = vo.Type,
					ParentId = vo.ParentId
				}).ExecuteCommand();
				return SuccessResult(true);
			}
			catch (Exception ex)
			{
				LogError(ex, "添加权限失败");
				return ErrorResult("添加权限失败", false);
			}
		}
		/// <summary>
		/// 删除权限
		/// </summary>
		/// <param name="permissionId">权限Id</param>
		/// <returns></returns>
		[HttpDelete("{permissionId}")]
		public ResponseResult<bool> Delete(string permissionId)
		{
			try
			{
				_dbClient.Deleteable<PermissionDTO>(p => p.PermissionId == permissionId).ExecuteCommand();
				return SuccessResult(true);
			}
			catch (Exception ex)
			{
				LogError(ex, "删除权限失败");
				return FailedResult("删除权限失败", false);
			}
		}
		/// <summary>
		/// 修改权限
		/// </summary>
		/// <param name="vo">修改实体</param>
		/// <returns></returns>
		[HttpPut]
		public ResponseResult<bool> Update([FromBody] RequestEditPermissionVO vo)
		{
			try
			{
				_dbClient.Updateable<PermissionDTO>(new PermissionDTO()
				{
					PermissionId = vo.PermissionId,
					PermissionName = vo.PermissionName,
					PermissionCode = vo.PermissionCode.ToLower(),
					Url = vo.Url,
					Icon = vo.Icon,
					Order = vo.Order,
					Type = vo.Type,
					ParentId = vo.ParentId
				})
				.ExecuteCommand();
				return SuccessResult(true);
			}
			catch (Exception ex)
			{
				LogError(ex, "修改权限失败");
				return FailedResult("修改权限失败", false);
			}
		}

		/// <summary>
		/// 根据类型获取权限树
		/// </summary>
		/// <param name="type">权限类型</param>	
		/// <returns></returns>
		[HttpGet("tree/{type}")]
		public ResponseResult<List<PermissionDTO>> GetTree(string type)
		{
			try
			{
				var list = _dbClient.Queryable<PermissionDTO>()
					.Where(p => p.Type == type)
					.OrderBy(p => p.Order)//按排序规则排序
					.ToTree(d => d.Children, d => d.ParentId, null);

				return SuccessResult(list);
			}
			catch (Exception ex)
			{
				LogError(ex, "获取权限树失败");
				return ErrorResult<List<PermissionDTO>>("获取权限树失败", null);
			}
		}
		/// <summary>
		/// 根据类型获取权限树
		/// </summary>
		/// <param name="type">权限类型</param>	
		/// <returns></returns>
		[HttpGet("mytree/{type}")]
		public ResponseResult<List<PermissionDTO>> GetMyTree(string type)
		{
			var token = Request.Headers["token"].ToString();
			string userId = TokenUtil.GetValueFromJwtToken(token, "sub").ToString();
			try
			{
				//默认按角色权限，否则内置用户或内置角色则获取所有权限，避免未添加权限时超级管理员使用功能不全
				List<PermissionDTO> listResult = new List<PermissionDTO>();
				if (userId == _configuration["AppConfig:SystemId"])
				{
					listResult = _dbClient.Queryable<PermissionDTO>()
					.Where(p => p.Type == type)
					.OrderBy(p => p.Order)//按排序规则排序
					.ToTree(d => d.Children, d => d.ParentId, null);
				}
				else
				{
					//TODO 根据用户状态返回受限的权限列表
					var user = _dbClient.Queryable<UserDTO>().First(u => u.UserId == userId);
					if (user != null && user.Status == "02")
					{//不返回添加、删除、修改等权限，只返回查询权限

					}
					var role = _dbClient.Queryable<UserRoleDTO>().First(o => o.UserId == userId);
					if (role != null)
					{
						listResult = _dbClient.Queryable<PermissionDTO>()
							.InnerJoin<RolePermissionDTO>((p, r) => p.PermissionId == r.PermissionId && r.RoleId == role.RoleId)
							.Where((p, r) => p.Type == type)
							.ToTree(d => d.Children, d => d.ParentId, null);
					}
				}

				return SuccessResult(listResult);
			}
			catch (Exception ex)
			{
				LogError(ex, "获取用户权限树失败");
				return ErrorResult<List<PermissionDTO>>("获取用户权限树失败", null);
			}
		}
	}
}
